import config from '@/config/config.js';
import {promisic,utils} from "./utils";


class Http {
	constructor(arg) {
		
	}
	//封装请求
	static async request({url, data = {}, method = 'GET', header={}}){
		let thisHeader = Object.assign(header,{
			"Authorization": utils.getStorage("token") ? "Bearer " + utils.getStorage("token") : null,
			"Access-Control-Allow-Origin":"*"
		})
		console.log(`${config.apiBaseUrl}${url}`)
		const res = await promisic(uni.request)({
			url:`${config.apiBaseUrl}${url}`,
			data,
			method,
			sslVerify:false,
			header:thisHeader
		})
		uni.hideLoading()
		if(res.header.refresh == 'true'){
			uni.request({
				url: `${config.apiBaseUrl}refreshToken`,
				method:"POST",
				sslVerify:false,
				header:{
					Authorization: "Bearer " + utils.getStorage("token")
				},
				success(res) {
					console.log(res.data)
					utils.setStorage("token",res.data)
					console.log(utils.getStorage("token"))
				}
			})
			return res.data;
		}
		
		if(config.authCode.includes(res.data.code)){
			utils.removeStorage("token")
			uni.redirectTo({
				url:"../login/login",
				complete:(e)=> {
					console.log(e)
				}
			})
			uni.showToast({
				icon:'none',
			    title: "登录过期，请重新登录",
			    duration: 2000
			});
		}
		console.log(res)
		uni.hideLoading()
		return res.data;
	}
	
	//封装请求
	static async uploadFiles({url,files = {},data = {}, header={}}){
		let thisHeader = Object.assign(header,{
			"Authorization": utils.getStorage("token") ? "Bearer " + utils.getStorage("token") : null,
			"Access-Control-Allow-Origin":"*"
		})
		console.log(`${config.apiBaseUrl}${url}`)
		const res = await promisic(uni.uploadFile)({
			url:`${config.apiBaseUrl}${url}`,
			formData:data,
			sslVerify:false,
			header:thisHeader,
			files
		})
		uni.hideLoading()
		return JSON.parse(res.data);
	}
	
	//封装请求
	static async uploadFile({url,filePath, name,data = {}, header={}}){
		let thisHeader = Object.assign(header,{
			"Authorization": utils.getStorage("token") ? "Bearer " + utils.getStorage("token") : null,
			"Access-Control-Allow-Origin":"*"
		})
		console.log(`${config.apiBaseUrl}${url}`)
		const res = await promisic(uni.uploadFile)({
			url:`${config.apiBaseUrl}${url}`,
			formData:data,
			sslVerify:false,
			header:thisHeader,
			filePath,
			name
		})
		console.log(res)
		uni.hideLoading()
		return JSON.parse(res.data);
	}
}

export {
	Http
}